package cn.middle.remote.handler.decodec;

import java.util.List;

import cn.middle.remote.message.ReplyMessageSignal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class ReplySignalCodec implements Codec<ReplyMessageSignal> {
	
	//消息ID + 目标地址客户端标识 + code + 信息 +   接口名称 + 数据
		private int mutableLength = 4 + 4 + 4 + 4 + 4 + 4;

	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		if(in.readableBytes() < mutableLength) {
			in.readerIndex(beginIndex);
			return ;
		}
		
		int msgLength = in.readInt();
		if(!CodecUtil.checkLength(in, msgLength + 4 + 4 + 4 + 4 + 4, beginIndex)) {
			return ;
		}
		String msgId = CodecUtil.context(in, msgLength);
		
		int remoteClientId = in.readInt();
		int code = in.readInt();
		int messageLength = in.readInt();
		if(!CodecUtil.checkLength(in, messageLength  + 4 + 4, beginIndex)) {
			return ;
		}
		
		String message = CodecUtil.context(in, messageLength);
		int interfaceLength = in.readInt();
		if(!CodecUtil.checkLength(in, interfaceLength + 4, beginIndex)) {
			return ;
		}
		String interfaceName = CodecUtil.context(in, interfaceLength);
		
		int dataLength = in.readInt();
		if(!CodecUtil.checkLength(in, dataLength, beginIndex)) {
			return ;
		}
		
		//如何还原为对象还没想好，先暂时使用数组
		byte[] data = CodecUtil.data(in, dataLength);
		
		ReplyMessageSignal signal = new ReplyMessageSignal();
		signal.setId(msgId);
		signal.setRemoteAddressClientId(remoteClientId);
		signal.setCode(code);
		signal.setMessage(message);
		signal.setInterfaceName(interfaceName);
		signal.setData(data);
		out.add(signal);
	}

	@Override
	public void encode(ChannelHandlerContext ctx, ReplyMessageSignal msg, ByteBuf out) throws Exception {
		out.writeBytes(msg.toData());	
	}



}
